package com.sgj.singleton.type4;

import java.util.Objects;

/**
 * 单例模式
 * 懒汉式（线程安全案例）
 * @Author: Guoji Shen
 * @Date: 2021/11/11 13:58
 */
public class SingletonTest04 {
    public static void main(String[] args) {
        // 测试
        Singleton instance = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance == instance2);
        System.out.println("instance.hashCode = " + instance.hashCode());
        System.out.println("instance2.hashCode = " + instance2.hashCode());
    }
}

class Singleton {
    private static Singleton instance;

    private Singleton() {

    }

    // 提供一个静态的公有方法，加入同步处理的代码，解决线程安全问题
    // 会出现多次同步的情况
    public static synchronized Singleton getInstance() {
        if (Objects.isNull(instance)) {
            instance = new Singleton();
        }
        return instance;
    }
}